import { ref } from 'vue'
import { createPinia, defineStore } from 'pinia'
import { local } from '@/utils/storage'

export const STORE_KEY = '@app/store'

export const useAppStore = defineStore('app-store', () => {
  const userInfo = ref<UserInfo>()
  const videos = ref<Videos>()
  const thems = ref<Thems>()
  const cachePage = ref<CachePage>()

  return {
    userInfo,
    videos,
    thems,
    cachePage,
    setUserInfo(info?: UserInfo) {
      userInfo.value = info
    },
    setvideos(info?: Videos) {
      videos.value = info
    },
    setcachePage(info?: CachePage) {
      cachePage.value = info
    },
    setthems(info?: Thems) {
      thems.value = info
    },
  }
})


const pinia = createPinia()

pinia.use((ctx) => {
  // 还原本地 store
  const localState = local.get<Record<string, any>>(STORE_KEY)
  if (localState) {
    try {
      for (const [key, val] of Object.entries(localState)) {
        ctx.store[key] = val
      }
    } catch { }
  }

  // 将 store 同步到 localStorage
  ctx.store.$subscribe((mutation, state) => {
    local.set(STORE_KEY, state)
  })
})

export default pinia
